<template>
  <view class="notice-container">
    <view class="notice-search">
      <uni-search-bar placeholder="请输入搜索内容" />
    </view>

    <view class="notice-list">
      <!-- 系统通知 -->
      <view
        class="notice-item"
        :class="hasUnreadSystemNotice ? 'unread' : ''"
        @click="viewDetail"
      >
        <view class="notice-icon-wrapper">
          <image class="notice-icon" :src="systemData.noticeLogoUrl" />
          <uni-badge
            v-if="hasUnreadSystemNotice"
            text=""
            type="error"
            class="notice-badge"
          />
        </view>
        <view class="notice-content">
          <view class="notice-title">系统通知</view>
          <view class="notice-desc">{{ systemData.title }}</view>
        </view>
        <view class="notice-time">{{ systemData.time }}</view>
      </view>

      <!-- 交易通知 -->
      <view
        class="notice-item"
        v-for="(item, index) in noticeList"
        :key="index"
        @click="viewTrade"
      >
        <image class="notice-icon" :src="item.storeLogoUrl" />
        <view class="notice-content">
          <view class="notice-title">{{ item.storeName }}</view>
          <view class="notice-desc">{{ item.noticePrompt }}</view>
        </view>
        <view class="notice-time">{{ item.tradeTime }}</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { hasUnreadNotice, getTradeNotice } from '../../utils/api';

const systemData = ref({
  noticeLogoUrl: '../../../static/system.png',
  title: '',
  time: '',
  id: null,
  is_read: false,
});

// 控制是否显示系统通知小红点
const hasUnreadSystemNotice = ref(true);

// 交易通知列表
const noticeList = ref([]);

onMounted(async () => {
  try {
	console.log("开始获取")
    // 获取系统通知轻量级接口，只需知道是否有未读，这个轻量级接口只返回必要信息和是否已读
    const res = await hasUnreadNotice();
    const latestNotice = res.data && res.data[0];
    if (latestNotice) {
      systemData.value = {
        ...systemData.value,
        title: latestNotice.title,
        time: latestNotice.time,
        id: latestNotice.id,
        is_read: latestNotice.is_read,
      };
	  // 新来的消息时未读，所以改成显示小红点
      hasUnreadSystemNotice.value = !latestNotice.is_read;
    }

    // 获取交易通知列表
    const tradeRes = await getTradeNotice();
    noticeList.value = tradeRes?.data || [];
  } catch (error) {
    console.error('加载通知数据失败:', error);
	// 模拟数据，供开发测试用
	  noticeList.value = [
	    {
	      storeLogoUrl: '../../../static/walmart.png',
	      storeName: '沃尔玛超市（平安路店）',
	      noticePrompt: '尊敬的客户：您好！您已在本地消费您已在...',
	      tradeTime: '昨天 21:00',
	    },
	    {
	      storeLogoUrl: '../../../static/walmart.png',
	      storeName: '沃尔玛超市（南门店）',
	      noticePrompt: '您的订单已发货，请注意查收。',
	      tradeTime: '今天 09:30',
	    }
	  ];
  }
});

async function viewDetail() {
  // 如果是未读消息，标记为已读
  if (!systemData.value.is_read && systemData.value.id) {
    try {
      await markMessagesAsRead({
        messageIds: [systemData.value.id],
      });
      hasUnreadSystemNotice.value = false;
      systemData.value.is_read = true;
    } catch (error) {
      console.error('标记消息已读失败:', error);
    }
  }
  uni.navigateTo({
    url: '/pages/C/notice/detail',
  });
}

function viewTrade() {
  uni.navigateTo({
    url: '/pages/C/notice/trade',
  });
}
</script>

<style src="./index.css"></style>
